<?php

namespace app\common\cachemodel\zl2;

use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl2SurpriseCouponDiscount extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl2_surprise_coupon_discount';

    protected $cacheModel = 'astro_fortune.surprise_coupon_discount';

    /**
     * 获取 优惠券折扣券数据
     * @param int $sid
     * @return array
     * @throws \Exception
     */
    public function getCouponDiscountData(int $sid)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $sid)->getDataAndSet(function () use ($sid)
        {
            try
            {
                $data = $this->where(['pid' => $sid, 'status' => 1])->column('cid,probability', 'id');

                foreach ($data as $id => $datum)
                {
                    $data[$id] = json_encode($datum, JSON_UNESCAPED_UNICODE);
                }
                return $data;
            }
            catch (\Exception $e)
            {
                Log::write('Zl2SurpriseCouponDiscount model => getCouponDiscountData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                return [];
            }
        });

        $resData = ['list' => [], 'max' => 0];
        if ($data)
        {
            $totalProbability = 0;
            foreach ($data as $id => $datum)
            {
                $d = json_decode($datum, true);
                $totalProbability += $d['probability'];
                $resData['list'][$id] = $d;
            }
            $resData['max'] = $totalProbability;
        }

        return $resData;
    }
}